import authApi from '@/api/common/auth'
import config from '@/config'
import { defineStore } from 'pinia'
import { ref, computed } from 'vue';

export const useUserStore = defineStore("user", () => {
  const id: any = ref(null)
  const name = ref('')
  const name2 = ''
  const name3 = {
    name: ''
  }

  const refreshTokenLockPromise = ref(null as Promise<boolean> | null)
  const hasAuthInfo = computed(() => id.value != null)

  async function login(userLogin: any) {
    const res: any = await authApi.login(userLogin)
    if (res.data.status == "SUCCESS") {
      localStorage.setItem(config.token.accessKey, res.data.accessToken);
      localStorage.setItem(config.token.refreshKey, res.data.refreshToken);
      localStorage.setItem("isRemember", userLogin.isRemember);
    }
    return res;
  }
  async function refreshToken(): Promise<boolean> {
    let refreshToken = localStorage.getItem(config.token.refreshKey);
    if (!refreshToken) {
      return false
    }
    if (refreshTokenLockPromise.value != null) {
      return await refreshTokenLockPromise.value;
    }
    let refreshTokenLockPromiseResolve: any;
    refreshTokenLockPromise.value = new Promise(resolve => {
      refreshTokenLockPromiseResolve = resolve
    })
    let accessToken = localStorage.getItem(config.token.accessKey);
    let isRemember = localStorage.getItem("isRemember") == "true" ? true : false;

    const res: any = await authApi.refreshToken({ accessToken, refreshToken, isRemember })
    let isSuccess: boolean = false
    if (res.data.status == "SUCCESS") {
      localStorage.setItem(config.token.accessKey, res.data.accessToken);
      localStorage.setItem(config.token.refreshKey, res.data.refreshToken);
      isSuccess = true
    }
    refreshTokenLockPromiseResolve && refreshTokenLockPromiseResolve(isSuccess);
    refreshTokenLockPromise.value = null
    return isSuccess;
  }
  //清空登录信息
  function clearAuth() {
    localStorage.removeItem(config.token.accessKey);
    localStorage.removeItem(config.token.refreshKey);
    window.location.reload();
  }
  async function logout() {
    const res = await authApi.logout()
    clearAuth()
  }
  const menus = ref<Array<any>>([])
	const permissionMenus = ref<Array<any>>([])
  return {
    id,
    name,
    name2, name3,
    refreshTokenLockPromise,
    hasAuthInfo,
    menus,
    permissionMenus,
    login,
    refreshToken,
    logout,
    clearAuth
  }
});
const user = {
  state: {
    id: null,
    name: '',
    //重刷token的锁
    refreshTokenLockPromise: null
  },
  getters: {
    hasAuthInfo: state => {
      return state.id != null
    }
  },
  mutations: {
    SET_ID(state, id) {
      state.id = id
    },
    SET_NAME(state, name) {
      state.name = name;
    },
    SET_ACCESS_TOKEN(state, name) {
      state.name = name
    },
    SET_REFRESH_TOKEN(state, refreshToken) {
      state.name = name
    },
    SET_REFRESH_TOKEN_LOCK_PROMISE(state, lockPromise) {
      state.refreshTokenLockPromise = lockPromise
    },
    SET_REFRESH_TOKEN_LOCK_PROMISE_RESOLVE(state, lockPromiseResolve) {
      state.refreshTokenLockPromiseResolve = lockPromiseResolve
    }
  },
  actions: {
    login({ commit }, user) {
      return new Promise((resolve, reject) => {
        authApi.login(user).then(res => {
          if (res.data.status == "SUCCESS") {
            localStorage.setItem(config.token.accessKey, res.data.accessToken);
            localStorage.setItem(config.token.refreshKey, res.data.refreshToken);
            localStorage.setItem("isRemember", user.isRemember);
            resolve(res);
          } else {
            reject(res);
          }
        }).catch(() => {
          reject(res);
        })
      })
    },
    refreshToken({ state, commit }) {
      let lock = state.refreshTokenLockPromise;
      if (lock) {
        return lock;
      }
      return new Promise((resolve, reject) => {
        let refreshToken = localStorage.getItem(config.token.refreshKey);
        if (!refreshToken) {
          resolve(false);
          return;
        }
        let lockPromiseResolve;
        commit("SET_REFRESH_TOKEN_LOCK_PROMISE", new Promise(resolve => {
          lockPromiseResolve = resolve
        }))
        let accessToken = localStorage.getItem(config.token.accessKey);
        let isRemember = localStorage.getItem("isRemember") == "true" ? true : false;
        authApi.refreshToken({ accessToken, refreshToken, isRemember }).then(res => {
          if (res.data.status == "SUCCESS") {
            localStorage.setItem(config.token.accessKey, res.data.accessToken);
            localStorage.setItem(config.token.refreshKey, res.data.refreshToken);
            resolve(true);
            lockPromiseResolve && lockPromiseResolve(true);
          } else {
            resolve(false);
            lockPromiseResolve && lockPromiseResolve(false);
          }
          localStorage.removeItem("lock");
          commit("SET_REFRESH_TOKEN_LOCK_PROMISE", null);
        })

      });
    },
    //清空登录信息
    clearAuth() {
      localStorage.removeItem(config.token.accessKey);
      localStorage.removeItem(config.token.refreshKey);
      window.location.reload();
    },
    logout({ commit, dispatch }) {
      authApi.logout().then(() => {
        dispatch("clearAuth");
      })
    }
  }
}
export default user
